package com.sunshine.lnuplus.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.NonNull;

import com.sunshine.lnuplus.utils.FileHelper;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoadWeatherService extends Service {
    public LoadWeatherService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        loadWeather();
    }

    /**
     * 下载天气
     */
    private void loadWeather() {
        String url = "https://www.tianqiapi.com/api/?version=v6&ip&appid=84958684&appsecret=gHjgc8wG";
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                stopSelf();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                ResolveWeather(response.body().string());
            }
        });
    }

    //解析weather的json信息
    private void ResolveWeather(String WeatherData){
        try {
            JSONObject jsonObject = new JSONObject(WeatherData);
            String city = jsonObject.getString("city");
            int tem = jsonObject.getInt("tem");
            String weather = jsonObject.getString("wea");
            FileHelper.weatherToSp(this,city,tem,weather,handler); //储存到sp中
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(1==msg.what) stopSelf();
        }
    };
}
